package com.jeecg.demo.controller;

import com.jeecg.demo.entity.AnnouncementEntity;
import com.jeecg.demo.service.AnnouncementServiceI;
import com.jeecg.demo.util.PopupDataBindUtil;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * @Description: ANNOUNCEMENT
 * @author onlineGenerator
 * @date 2018-11-23 10:19:21
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/announcementController")
public class AnnouncementController extends BaseController {
    private static final Logger logger = LoggerFactory
            .getLogger(AnnouncementController.class);

    @Autowired
    private AnnouncementServiceI announcementService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private PopupDataBindUtil bindUtil;

    /**
     * ANNOUNCEMENT列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request, String type) {
        request.setAttribute("type", type);
        return new ModelAndView("com/jeecg/announcement/announcementList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param user
     * @throws Exception
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(AnnouncementEntity announcement,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, String type) throws Exception {
        CriteriaQuery cq = new CriteriaQuery(AnnouncementEntity.class, dataGrid);
        // 查询条件组装器
        // 如果绑定报表数据，则更新排序格式，将新增的虚拟列改为原表中对应列
        dataGrid.setSort(dataGrid.getSort().replace("username", "userid"));

        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                announcement, request.getParameterMap());
        try {
            // 自定义追加查询条件
            if ("verify".equals(type)) {
                cq.eq("zhuangt", "1");
                cq.add();
            }
            else if ("info".equals(type)) {
                // cq.eq("zhuangt", "2");
                cq.add();
            }
        }
        catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.announcementService.getDataGridReturn(cq, true);

        // 绑定非字典表数据
        bindUtil.BindDDName(dataGrid, "SYS_USER", "username", "userid",
                "userid", "username");


        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 删除ANNOUNCEMENT
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(AnnouncementEntity announcement,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        announcement = systemService.getEntity(AnnouncementEntity.class,
                announcement.getId());
        message = "删除成功";
        try {
            announcementService.delete(announcement);
            systemService.addLog(message, Globals.Log_Type_DEL,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除ANNOUNCEMENT
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                AnnouncementEntity announcement = systemService.getEntity(
                        AnnouncementEntity.class, Integer.parseInt(id));
                announcementService.delete(announcement);
                systemService.addLog(message, Globals.Log_Type_DEL,
                        Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加ANNOUNCEMENT
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(AnnouncementEntity announcement,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "添加成功";
        try {
        	Date time=new Date();

        	announcement.setTrademode(announcement.getAnnountype());
        	announcement.setAnnountime(time);
        	announcement.setZhuangt("1");
            announcementService.save(announcement);
            systemService.addLog(message, Globals.Log_Type_INSERT,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 审核ANNOUNCEMENT
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doVerify")
    @ResponseBody
    public AjaxJson doVerify(AnnouncementEntity announcement,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "审核成功";
        AnnouncementEntity t = announcementService.get(
                AnnouncementEntity.class, announcement.getId());
        try {
            t.setZhuangt("2");
            announcementService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "审核失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * ANNOUNCEMENT审核页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goVerify")
    public ModelAndView goVerify(AnnouncementEntity announcement,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(announcement.getId())) {
            announcement = announcementService.getEntity(
                    AnnouncementEntity.class, announcement.getId());
            req.setAttribute("action", "announcementController.do?doVerify");
            String announcontent = announcement.getAnnouncontent();
            if (StringUtils.isEmpty(announcontent)||"<CLOB>".equals(announcontent)) {
            	announcement.setAnnouncontent("");
			}
            req.setAttribute("announcementPage", announcement);
            req.setAttribute("flags","disabled");
        }
        return new ModelAndView("com/jeecg/announcement/announcement-update");
    }

    /**
     * 更新ANNOUNCEMENT
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(AnnouncementEntity announcement,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "更新成功";
        AnnouncementEntity t = announcementService.get(
                AnnouncementEntity.class, announcement.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(announcement, t);
            announcementService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * ANNOUNCEMENT新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(AnnouncementEntity announcement,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(announcement.getId())) {
            announcement = announcementService.getEntity(
                    AnnouncementEntity.class, announcement.getId());
            req.setAttribute("announcementPage", announcement);
        }
        return new ModelAndView("com/jeecg/announcement/announcement-add");
    }

    /**
     * ANNOUNCEMENT编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(AnnouncementEntity announcement,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(announcement.getId())) {
            announcement = announcementService.getEntity(
                    AnnouncementEntity.class, announcement.getId());
            String announcontent = announcement.getAnnouncontent();
            if (StringUtils.isEmpty(announcontent)||"<CLOB>".equals(announcontent)) {
            	announcement.setAnnouncontent("");
			}
            req.setAttribute("action", "announcementController.do?doUpdate");
            req.setAttribute("announcementPage", announcement);
            req.setAttribute("flags", req.getParameter("flags"));
        }
        return new ModelAndView("com/jeecg/announcement/announcement-update");
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "announcementController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(AnnouncementEntity announcement,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, ModelMap modelMap, String ids) {
        CriteriaQuery cq = new CriteriaQuery(AnnouncementEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                announcement, request.getParameterMap());
        cq.in("id", bindUtil.idsToIntegerArray(ids));
        cq.add();
        List<AnnouncementEntity> announcements = this.announcementService
                .getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "ANNOUNCEMENT");
        modelMap.put(NormalExcelConstants.CLASS, AnnouncementEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams(
                "ANNOUNCEMENT列表", "导出人:"
                        + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, announcements);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(AnnouncementEntity announcement,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "ANNOUNCEMENT");
        modelMap.put(NormalExcelConstants.CLASS, AnnouncementEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams(
                "ANNOUNCEMENT列表", "导出人:"
                        + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request,
            HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<AnnouncementEntity> listAnnouncementEntitys = ExcelImportUtil
                        .importExcel(file.getInputStream(),
                                AnnouncementEntity.class, params);
                for (AnnouncementEntity announcement : listAnnouncementEntitys) {
                    announcementService.save(announcement);
                }
                j.setMsg("文件导入成功！");
            }
            catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(e.getMessage());
            }
            finally {
                try {
                    file.getInputStream().close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }
   public String[] getPocode(){

	   List<Map<String, Object>> list=systemService.findForJdbc("select pocode from postorder where isvalid=1", null);
	   String[] arrs=new String[list.size()];
	   int i=0;
	   for(Map<String, Object> maps :list){

		   //Map<String, Object> maps=list.get(i);

		 for(String key : maps.keySet()){
	           if(key.equals("POCODE")){

	        	   String value = (String)maps.get(key);
	        	   arrs[i]=value;
	        	   i++;
	           }
	       }
	   }

       return arrs;
	   }
}
